<template>
  <div>
    <el-dialog
      v-bind="$attrs"
      v-on="$listeners"
      @open="onOpen"
      :before-close="beforeClose"
      @close="onClose"
      title="Dialog Titile"
    >
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <el-form-item label="视频标题" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入视频标题"
                :maxlength="128"
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                placeholder="请输入视频描述"
                :maxlength="1024"
                :autosize="{minRows: 7, maxRows: 7}"
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传封面" prop="coverURL">
              <el-upload
                ref="coverURL"
                :file-list="coverURLfileList"
                :action="coverURLAction"
                :limit="1"
                :before-upload="coverURLBeforeUpload"
                list-type="picture-card"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的image/*文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频分类ID" prop="cateId">
              <el-select
                v-model="formData.cateId"
                placeholder="请选择视频分类ID"
                clearable
                :style="{width: '100%'}"
              ></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视频标签" prop="tags">
              <el-select
                v-model="formData.tags"
                allow-create
                filterable
                default-first-option
                placeholder="请选择视频标签"
                multiple
                clearable
                :style="{width: '100%'}"
              ></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转码模板组ID" prop="templateGroupId">
              <el-select
                v-model="formData.templateGroupId"
                placeholder="请选择转码模板组ID"
                clearable
                :style="{width: '100%'}"
              >
                <el-option
                  v-for="(item, index) in listTemplateGroup"
                  :key="index"
                  :label="item.name"
                  :value="item.transcodeTemplateGroupId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="视频" prop="file">
              <div>
                <input
                  type="file"
                  id="fileUpload"
                  @click="fileClick($event)"
                  @change="fileChange($event)"
                />
                <label class="status">
                  上传状态:
                  <span>{{statusText}}</span>
                </label>
              </div>
              <div class="upload-type">
                <button @click="authUpload" :disabled="uploadDisabled">开始上传</button>
                <button @click="pauseUpload" :disabled="pauseDisabled">暂停</button>
                <button :disabled="resumeDisabled" @click="resumeUpload">恢复上传</button>
                <span class="progress" v-if="authProgress>0">
                  <el-progress :percentage="authProgress"></el-progress>
                </span>
              </div>
              <div>只能上传不超过 500MB 的video/*文件</div>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  uploadAuth,
  listTemplateGroup,
  refreshUploadVideo
} from "@/api/aliyun/vod.js";

export default {
  inheritAttrs: false,
  components: {},
  props: [],
  data() {
    return {
      formData: {
        title: undefined,
        description: undefined,
        coverURL: null,
        cateId: undefined,
        tags: [],
        templateGroupId: undefined,
        fileName: undefined,
        fileSize: undefined
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入视频标题",
            trigger: "blur"
          }
        ],
        description: [],
        cateId: [],
        tags: [],
        templateGroupId: []
      },
      listTemplateGroup: [],
      coverURLAction: "http://192.168.0.132:8080/oss/uploading-image",
      coverURLfileList: [],
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: ""
    };
  },
  computed: {},
  watch: {},
  created() {
    listTemplateGroup().then(res => {
      this.listTemplateGroup = res.data;
    });
  },
  mounted() {},
  methods: {
    onOpen() {},
    onClose() {
      this.$refs["elForm"].resetFields();
      this.uploadDisabled = true;
      this.resumeDisabled = true;
      this.pauseDisabled = true;
    },
    beforeClose(done) {
      if (this.valiUpload()) {
        done();
      }
    },
    close() {
      this.$emit("update:visible", false);
    },
    coverURLBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      let isAccept = new RegExp("image/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择image/*类型的文件");
      }
      return isRightSize && isAccept;
    },
    valiUpload() {
      if (this.authProgress > 0 && this.authProgress < 100) {
        this.$message.warning("文件正在上传中...");
        return false;
      }
      return true;
    },
    fileClick(e) {
      this.$refs["elForm"].validate(valid => {
        if (!valid) {
          this.$message.warning("抱歉请根据表单提示，填写相关信息");
          e.preventDefault();
        }
      });
      if (!this.valiUpload()) {
        e.preventDefault();
      }
    },
    fileChange(e) {
      let file = e.target.files[0];
      if (!file) {
        this.$message.error("请选择您要上传的视频");
        return;
      }
      this.formData.fileName = file.name;
      this.formData.fileSize = file.size;
      //效验文件是否合法
      let isRightSize = file.size / 1024 / 1024 < 500;
      if (!isRightSize) {
        this.$message.error("文件大小超过 500MB");
      }
      let isAccept = new RegExp("video/*").test(file.type);
      if (!isAccept) {
        this.$message.error("应该选择video/*类型的文件");
      }
      this.uploader = this.createUploader();
      //追加进入阿里SDK
      this.uploader.addFile(file, null, null, null, null);
      this.pauseDisabled = true;
      this.authProgress = 0;
    },
    authUpload() {
      if (!this.formData.fileName) {
        this.$message.error("请选择您要上传的视频");
        return;
      }
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
      }
    },
    // 暂停上传
    pauseUpload() {
      if (this.uploader !== null) {
        this.uploader.stopUpload();
        this.resumeDisabled = false;
        this.pauseDisabled = true;
      }
    },
    // 恢复上传
    resumeUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.resumeDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader(type) {
      let self = this;
      let uploader = new AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1048576,
        parallel: 5,
        retryCount: 3,
        retryDuration: 2,
        region: "cn-shanghai", //上传储存地址，自己填
        userId: "1006469311405512", //阿里云账号id，必填
        // 添加文件成功
        addFileSuccess: function(uploadInfo) {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
          self.statusText = "添加文件成功, 等待上传...";
        },
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          const loading = self.$loading({
            lock: true,
            text: "获取凭证"
          });
          if (!uploadInfo.videoId) {
            uploadAuth(self.formData)
              .then(res => {
                let uploadAuth = res.data.uploadAuth;
                let uploadAddress = res.data.uploadAddress;
                let videoId = res.data.videoId;
                self.statusText = "文件开始上传...";
                self.uploadDisabled = true;
                self.pauseDisabled = false;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  uploadAuth,
                  uploadAddress,
                  videoId
                );
                loading.close();
              })
              .catch(err => {
                loading.close();
              });
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            refreshUploadVideo(uploadInfo.videoId)
              .then(res => {
                let uploadAuth = res.data.uploadAuth;
                let uploadAddress = res.data.uploadAddress;
                let videoId = res.data.videoId;
                self.statusText = "文件开始上传...";
                self.uploadDisabled = true;
                self.pauseDisabled = false;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  uploadAuth,
                  uploadAddress,
                  videoId
                );
                loading.close();
              })
              .catch(err => {
                loading.close();
              });
          }
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
          self.resumeDisabled = true;
          self.pauseDisabled = true;
          self.statusText = "文件上传成功!";
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          self.pauseDisabled = true;
          self.resumeDisabled = false;
          self.statusText = "文件上传失败!";
        },
        // 取消文件上传
        onUploadCanceled: function(uploadInfo, code, message) {
          self.statusText = "文件已暂停上传";
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function(uploadInfo, totalSize, progress) {
          let progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.statusText = "文件上传中...";
        },
        // 上传凭证超时
        onUploadTokenExpired: function(uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          refreshUploadVideo(uploadInfo.videoId).then(res => {
            let uploadAuth = res.data.UploadAuth;
            uploader.resumeUploadWithAuth(uploadAuth);
            self.statusText = "文件超时...";
          });
        },
        // 全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          self.statusText = "文件上传完毕";
        }
      });
      return uploader;
    },
    handelConfirm() {}
  }
};
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
